package com.qiwenshare.stock.common;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.request.OapiRobotSendRequest;
import com.dingtalk.api.response.OapiRobotSendResponse;
import com.taobao.api.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.service.spi.ServiceException;

@Slf4j
public class DingTalkUtil {

    public static String WEB_HOOK = "https://oapi.dingtalk.com/robot/send?access_token=%s";
    public static String DEFAULT_TOKEN = "9552d6280474a2b26cc84af38958db9af3ec4fa5bdaaccdc74d13727b6ad70d5";
//    https://oapi.dingtalk.com/robot/send?access_token=9552d6280474a2b26cc84af38958db9af3ec4fa5bdaaccdc74d13727b6ad70d5
    public static boolean send(String token, String message) {
        try {
            if(StringUtils.isEmpty(message)) {
                throw new ServiceException("消息内容不能为空");
            }
            String webhook  = StringUtils.isEmpty(token) ? String.format(WEB_HOOK, DEFAULT_TOKEN) : String.format(WEB_HOOK, token);
            DefaultDingTalkClient client = new DefaultDingTalkClient(webhook);
            OapiRobotSendRequest request = new OapiRobotSendRequest();
            request.setMsgtype("text");

            OapiRobotSendRequest.Text text = new OapiRobotSendRequest.Text();
            text.setContent(message);
            request.setText(text);

            OapiRobotSendResponse response = client.execute(request);

            if (response.isSuccess()) {
                log.info("Message sent successfully!");
                return Boolean.TRUE;
            } else {
                log.error("Failed to send message. Error code: " + response.getErrorCode() + ", error message: " + response.getErrmsg());
            }

        } catch (ApiException e) {
            log.error("dingding 消息发送异常", e);
        }
        return Boolean.FALSE;
    }


    public static void main(String[] args) {
        DingTalkUtil.send(null, "Hello, DingTalk!  这是一个下单测试消息！");
    }
}
